﻿using System;
using System.Web.Mvc;
using ZFine.Application.Project;
using ZFine.Code;
using ZFine.Domain.Entity;
using System.Linq;
using ZFine.Web;
using Entity.ProjectEnt;
using System.Collections.Generic;
using System.Text;
using System.Web;
using NPOI.HSSF.UserModel;
using NPOIDemo;
using WebGrease.Css.Extensions;
using System.IO;

namespace Logiv.WEB.Areas.Project.Controllers
{
    ///<summary>
    /// 股道控制器
    /// </summary>
    public class PathwayController : BaseController
    {
        private PathwayApp serverApp = new PathwayApp();
        private GudaoCarApp gudaocarApp = new GudaoCarApp();
        private CustomerAndThingsNameApp CTApp = new CustomerAndThingsNameApp();
        private CarTypeApp carTypeApp = new CarTypeApp();
        private CarriageBoxApp carriageBoxApp = new CarriageBoxApp();


        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetTreeSelectJson()
        {
            var data = serverApp.GetList();
            var treeList = new List<TreeSelectModel>();
            foreach (PathwayEntity item in data)
            {
                TreeSelectModel treeModel = new TreeSelectModel();
                treeModel.id = item.F_Id;
                treeList.Add(treeModel);
            }
            return Content(treeList.TreeSelectJson());
        }
        /// <summary>
        /// 导出数据(车辆汇总)
        /// </summary>
        /// <returns></returns>
        public ActionResult GetGridExportExcell()
        {
            try
            {
                var reuslt = gudaocarApp.GetListInclude(f => f.State == true);//获取当前有效的所有股道上的车

                ExcelBuilder excel = new ExcelBuilder();
                HSSFWorkbook wk = excel.ReadExcel(reuslt);

                string fileName = "站场车流表汇总" + DateTime.Now + ".xls";
                MemoryStream ms = new MemoryStream();
                wk.Write(ms);
                ms.Flush();
                //ms.Position = 0;
                RenderToBrowser(ms, fileName);

            }
            catch (Exception ex)
            {
                FileLog.Error(ex.ToString());
                throw;
            }

            return null;
        }
        /// <summary>
        ///  导出数据(箱号汇总)
        /// </summary>
        /// <returns></returns>
        public ActionResult GetGridExportCarBoxExcell()
        {
            try
            {
                var reuslt = gudaocarApp.GetListInclude(f => f.State == true);//获取当前有效的所有股道上的车
                string CarId = "";
                List<PathwayEntity> Pathways = new List<PathwayEntity>();
                if (reuslt != null) {
                    reuslt.ForEach(f =>
                    {
                        CarId += f.BelongCarriage == null ? "" : "'"+f.BelongCarriage.CarriageID + "',";
                        if (Pathways.Find(c => c.Name == f.BelongPathway.Name) == null) {
                            Pathways.Add(f.BelongPathway);
                        }
                    });
                    if (CarId.Length > 0)
                        CarId = CarId.Substring(0, CarId.Length - 1);
                }
                string sql = "select * from CarriageBox where ChangeBelongCarriageId in("+ CarId+")";
                List<CarriageBoxEntity> carriageBoxes = carriageBoxApp.GetList(sql);

                if (carriageBoxes.Count > 0) {
                    carriageBoxes.ForEach(f =>
                    {
                        var tempGudao = reuslt.Find(z => z.BelongCarriage.CarriageID == f.ChangeBelongCarriageId);
                        if (tempGudao != null && tempGudao.BelongPathway != null)
                        {
                            f.PathWayName = tempGudao.BelongPathway.Name;
                        }
                        else 
                        { 
                        
                        }
                    });
                }
                ExcelBuilder excel = new ExcelBuilder();
                HSSFWorkbook wk = excel.ReadExcelCarBox(carriageBoxes, Pathways);

                string fileName = "集装箱号汇总" + DateTime.Now + ".xls";
                MemoryStream ms = new MemoryStream();
                wk.Write(ms);
                ms.Flush();
                //ms.Position = 0;
                RenderToBrowser(ms, fileName);

            }
            catch (Exception ex)
            {

                throw;
            }

            return null;
        }

        static void RenderToBrowser(MemoryStream ms, string fileName)
        {
            byte[] bt = ms.ToArray();
            System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";

            //解决浏览器中文编码问题
            if (System.Web.HttpContext.Current.Request.UserAgent.ToLower().IndexOf("msie") > -1)
            {
                fileName = System.Web.HttpUtility.UrlPathEncode(fileName);
            }
            if (System.Web.HttpContext.Current.Request.UserAgent.ToLower().IndexOf("firefox") > -1)
            {
                System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
            }
            else
            {
                System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
            }
            int lengtn = bt.Length;
            System.Web.HttpContext.Current.Response.BinaryWrite(bt);
            System.Web.HttpContext.Current.Response.Flush();
            System.Web.HttpContext.Current.Response.End();

        }
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetGridJson(Pagination pagination)
        {
            try
            {
                var reuslt = serverApp.GetListN();
                var result = (from num in reuslt
                              select new PathwayEntity
                              {
                                  F_Id = num.F_Id,
                                  Name = num.Name,
                                  Length = num.Length,
                                  CarNumber = num.CarNumber,
                                  IsStatistics = num.IsStatistics,
                                  IsPermitThrough = num.IsPermitThrough,
                                  IsCounterpoint = num.IsCounterpoint,
                                  IsPaiche = num.IsPaiche
                              }).ToList();
                var data = new
                {
                    rows = result,
                    total = pagination.total,
                    page = pagination.page,
                    records = pagination.records
                };
                return Content(data.ToJson());

            }
            catch (Exception ex)
            {
                return null;
            }

        }
        /// <summary>
        /// 排车
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult ClearCarByGudao(string keyValue)
        {
            string msg = string.Empty;
            int code = serverApp.ClearCarinfo(keyValue, ref msg);
            if (code >= 0)
            {
                return Success("操作成功！");
            }
            else
            {
                return Error(msg);
            }

        }

        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult RetClearCarByGudao(string keyValue)
        {
            string msg = string.Empty;
            int code = serverApp.RetClearCarinfo(keyValue, ref msg);
            if (code >= 0)
            {
                return Success("回退操作成功！");
            }
            else
            {
                return Error(msg);
            }
        }

        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateInput(false)]
        public ActionResult SubmitForm(PathwayEntity ServerEntity, string keyValue)
        {
            serverApp.SubmitForm(ServerEntity, keyValue);
            return Success("操作成功！");
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetFormJson(string keyValue)
        {
            var data = serverApp.GetForm(keyValue);
            return Content(data.ToJson());
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetFormJson2(string keyValue)
        {
            Encoding utf8 = Encoding.UTF8;
            string code = HttpUtility.UrlDecode(keyValue.ToUpper(), utf8);
            var data = serverApp.GetForm(code);
            return Content(data.ToJson());
        }

        [HttpPost]
        [HandlerAjaxOnly]
        [HandlerAuthorize]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteForm(string keyValue)
        {
            var res = serverApp.DeleteForm(keyValue);
            if (res >= 0)
            {
                return Success("删除成功");
            }
            else if (res == -2)
            {
                return Error("该股道上还有车！不能进行删除操作！");
            }
            else if (res == -3)
            {
                return Error("还有未执行的计划！请执行完计划再进行此操作！");
            }
            else
            {
                return Error("操作不当！请重新操作！");
            }

        }

        /// <summary>
        /// 股道动态属性
        /// </summary>
        /// <returns></returns>
        public ActionResult Index2()
        {

            ViewBag.gudaocount = gudaocarApp.GetListInclude(f => f.State == true).Count;//获取当前有效的所有股道上的车
            return View();
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetGridJsonAuto(Pagination pagination)
        {
            try
            {
                var reuslt = gudaocarApp.GetListInclude(f => f.State == true);//获取当前有效的所有股道上的车
                var result = (from gudaoEntity in reuslt group gudaoEntity by gudaoEntity.BelongPathway into g select g).ToList();
                List<gudaohecheT> gudaoheche = new List<gudaohecheT>();
                if (result.Count > 0)
                {
                    result.ForEach(f =>
                    {
                        var temp = new gudaohecheT();
                        temp.gudanname = f.Key.Name.ToString();
                        temp.pingming = (from VAR in f group VAR by VAR.ThingsName into tt select tt.Key + ":" + tt.Count()).ToJson();
                        temp.carmun = f.ToList().Count;
                        temp.Sort = f.Key.ShowSort.Value;
                        gudaoheche.Add(temp);
                    });
                }
                var resultdata = (from VAR in gudaoheche select new { gudao = VAR.gudanname, Sort = VAR.Sort, xingxi = VAR.pingming.Replace("\"", "").Replace("[", "").Replace("]", ""), CarNumber = VAR.carmun }).ToList();

                #region 将空股道填入
                var gudaoAlllist = serverApp.GetList(f => f.State == true);
                if (gudaoAlllist != null && gudaoAlllist.Count > 0)
                {
                    gudaoAlllist.ForEach(f =>
                    {
                        bool exit = false;
                        resultdata.ForEach(t =>
                        {
                            if (t.gudao == f.Name)
                            {
                                exit = true;
                            }
                        });
                        if (!exit)
                        {
                            resultdata.Add(new { gudao = f.Name, Sort = f.ShowSort.Value, xingxi = "无车辆数据", CarNumber = 0 });
                        }
                        //if(gudaoAlllist.Find(z=>z.Name==))
                    });
                }
                var results = resultdata.OrderBy(f => f.Sort);
                #endregion

                var data = new
                {
                    rows = results,
                    total = pagination.total,
                    page = pagination.page,
                    records = pagination.records
                };
                return Content(data.ToJson());

            }
            catch (Exception ex)
            {
                return null;
            }

        }

        public ActionResult Edit(string keyValue)
        {
            try
            {
                var dd = gudaocarApp.GetForm(keyValue);
                ViewData["objs"] = gudaocarApp.GetForm(keyValue);
                ViewData["ThingsName"] = CTApp.GetList(f => f.Type == 0 && f.State == true);
                ViewData["Customers"] = CTApp.GetList(f => f.Type == 1 && f.State == true);
                ViewData["CarTypes"] = carTypeApp.GetList();
                return View();
            }
            catch (Exception ex)
            {
                FileLog.Error(ex);
            }
            return View();
        }

        public ActionResult DelCarByCarcode()
        {
            return View();
        }

    }

    public class gudaohecheT
    {
        public string gudanname { get; set; }
        public string pingming { get; set; }
        public int carmun { get; set; }
        public int Sort { get; set; }
    }
}